package com.ordos.recruit.module.user.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ordos.recruit.module.user.entity.SysSsoUserDto;
import com.ordos.recruit.module.user.entity.SysUserDto;
import com.ordos.recruit.module.user.entity.SysUserPo;
import com.ordos.recruit.module.user.entity.SysUserUpdatePwdDto;
import com.ordos.recruit.module.user.exception.UserLoginException;
import com.ordos.recruit.module.user.mapper.UserMapper;
import com.ordos.recruit.module.user.util.MD5Util;
import com.ordos.recruit.module.user.util.UserUtil;
import com.wonders.commons.util.exception.ApiException;
import com.wonders.commons.util.model.ValidatorResult;
import com.wonders.commons.util.response.ApiResponse;
import com.wonders.commons.validation.ObjectValidator;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.ordos.recruit.module.user.constant.Conf.USER_IS_ADMIN_STATUS_0;
import static com.ordos.recruit.module.user.constant.Conf.USER_USED_STATUS_0;

/**
 * UserService
 *
 * @author jin
 */
@Service
public class UserService {

    private final UserMapper userMapper;
    private final ObjectValidator objectValidator;

    public UserService(UserMapper userMapper, ObjectValidator objectValidator) {
        this.userMapper = userMapper;
        this.objectValidator = objectValidator;
    }

    /**
     * 获取用户信息.
     *
     * @param userName username
     * @param password password
     * @return 用户实体.
     */
    public SysUserPo getSysUserPo(String userName, String password) {
        LambdaQueryWrapper<SysUserPo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserPo::getPhoneNumber, userName);

        List<SysUserPo> sysUserPoList = userMapper.selectList(queryWrapper);
        if (CollUtil.isEmpty(sysUserPoList)) {
            throw new UserLoginException("用户名或密码错误..");
        }
        SysUserPo sysUserPo = sysUserPoList.get(0);

        if (CharSequenceUtil.isBlank(sysUserPo.getPassword()) || CharSequenceUtil.isBlank(sysUserPo.getPhoneNumber()) || "1".equals(sysUserPo.getUserStatusCode())) {
            throw new UserLoginException("此账号不可用, 请联系管理员.");
        }
        if(!sysUserPo.getPassword().equalsIgnoreCase(MD5Util.makeMD5(password))){
            throw new UserLoginException("用户名或者密码错误.");
        }

        //把密码置为空.
        sysUserPo.setPassword("");

        return sysUserPo;

    }

    /**
     * 保存用户信息.
     *
     * @param sysUserDto sysUserDto
     */
    public void saveSysUser(SysUserDto sysUserDto) {
        //校验请求入参参数.
        ValidatorResult<SysUserDto> sysUserDtoValidatorResult = objectValidator.objectValidator(sysUserDto);
        if(sysUserDtoValidatorResult.isHasErrors()){
            throw new ApiException(ApiResponse.dataError(0, sysUserDtoValidatorResult.getError()));
        }
        //判断用户是否存在
        boolean b = checkUserExist(sysUserDto);
        if (!b) {
            throw new UserLoginException("用户已存在，请勿重复添加！");
        }
        SysUserPo sysUserPo = new SysUserPo();

        //拷贝属性信息。
        BeanUtil.copyProperties(sysUserDto, sysUserPo);

        //设置密码.
        String password = MD5Util.makeMD5(sysUserDto.getPassword());
        sysUserPo.setPassword(password);
        //设置状态.
        sysUserPo.setUserStatusCode(USER_USED_STATUS_0);
        //管理员状态.
        sysUserPo.setUserIsAdmin(USER_IS_ADMIN_STATUS_0);

        userMapper.insert(sysUserPo);

    }

    /**
     * 修改用户密码信息.
     *
     * @param sysUserDto sysUserDto
     */
    public void updatePwd(SysUserUpdatePwdDto sysUserDto) {

        //校验请求入参.
        //基本校验
        ValidatorResult<SysUserUpdatePwdDto> validatorResult = objectValidator.objectValidator(sysUserDto);

        if (validatorResult.isHasErrors()) {
            throw new ApiException(ApiResponse.dataError(0, validatorResult.getError()));
        }

        LambdaQueryWrapper<SysUserPo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserPo::getPhoneNumber, sysUserDto.getPhoneNumber());
        queryWrapper.eq(SysUserPo::getCardId, sysUserDto.getCardId());

        List<SysUserPo> sysUserPoList = userMapper.selectList(queryWrapper);
        if (CollUtil.isEmpty(sysUserPoList)) {
            throw new UserLoginException("用户名不存在, 请填写正确的手机号..");
        }

        SysUserPo sysUserPo = sysUserPoList.get(0);

        //获取当前用户信息.
        SysSsoUserDto userByRequest = UserUtil.getUserByRequest();
        if (userByRequest == null || userByRequest.getUserid() == null || !userByRequest.getUserid().equals(sysUserPo.getId())) {
            throw new UserLoginException("请勿对其他账号进行操作, 请操作本人账号！");
        }
        //比较旧密码是否一致。，
        String originalPwd = MD5Util.makeMD5(sysUserDto.getOriginalPassword());
        if (sysUserPo.getPassword() != null && !sysUserPo.getPassword().equals(originalPwd)) {
            throw new UserLoginException("旧密码填写错误，请输入正确的旧密码！");
        }

        //设置新密码
        String newPwd = MD5Util.makeMD5(sysUserDto.getPassword());

        //执行修改密码操作。
        LambdaUpdateWrapper<SysUserPo> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(SysUserPo::getPassword, newPwd);
        updateWrapper.eq(SysUserPo::getId, sysUserPo.getId());
        updateWrapper.eq(SysUserPo::getPhoneNumber, sysUserPo.getPhoneNumber());

        //更新数据,
        int update = userMapper.update(null, updateWrapper);

        if (update <= 0) {
            throw new UserLoginException("密码更新失败, 当前账号未找到密码信息.");
        }


    }

    public boolean checkUserExist(SysUserDto sysUserDto){
        LambdaQueryWrapper<SysUserPo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserPo::getPhoneNumber, sysUserDto.getPhoneNumber())
                .or()
                .eq(SysUserPo::getCardId, sysUserDto.getCardId());
        Long l = userMapper.selectCount(queryWrapper);
        return l <= 0;
    }

}
